import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from utils import return_code
from django.conf import settings

class CurrentUser(object):
    def __init__(self, user_id,username,exp):
        self.user_id = user_id
        self.username = username
        self.exp = exp


class JwtTokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 读取用户提交的jwt token
        # 从url中获取token
        # token=request.query_params.get('token')
        # 从请求头中获取token 这里一定要关注前端的代码逻辑，传递的时候是传递在url还是请求头中，否则就获取不到token
        token =request.META.get('HTTP_AUTHORIZATION')
        if not token:
            raise AuthenticationFailed({'code':return_code.AUTH_FAILED,'error':'认证失败'})
        # jwt token校验
        try:
            payload=jwt.decode(token,key=settings.SECRET_KEY,algorithms=['HS256'])
            return CurrentUser(**payload),token
        except Exception as e:
            raise AuthenticationFailed({'code':return_code.AUTH_FAILED_ERROR,'error':'认证失败'})
        # return xx，xx
        # 抛出异常
    def authenticate_header(self, request):
        return 'Bearer realm="APT"'